<template>
  <div class="activity-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="title">
        <el-icon><Calendar /></el-icon>
        <span>志愿活动管理</span>
      </div>
      <div class="header-actions">
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>发布活动
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入活动标题"
            clearable
            prefix-icon="Search"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 160px">
            <el-option :label="getStatusText(0)" :value="0" />
            <el-option :label="getStatusText(1)" :value="1" />
            <el-option :label="getStatusText(2)" :value="2" />
            <el-option :label="getStatusText(3)" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        :empty-text="loading ? '加载中...' : '暂无数据'"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="活动标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="serviceType" label="服务类型" width="120" align="center" />
        <el-table-column prop="location" label="活动地点" width="180" show-overflow-tooltip />
        <el-table-column label="活动时间" width="340" align="center">
          <template #default="scope">
            {{ scope.row.startTime }} 至 {{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column label="招募人数" width="180" align="center">
          <template #default="scope">
            <el-tag type="info">已报名：{{ scope.row.signupCount }}/{{ scope.row.recruitNumber }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" effect="dark">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)" :disabled="!canEdit(scope.row.status)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="primary" link @click="handleView(scope.row)">
              <el-icon><View /></el-icon>查看
            </el-button>
            <el-button 
              :type="getActionButtonType(scope.row.status)"
              link 
              @click="handleStatusChange(scope.row)"
              :disabled="!canChangeStatus(scope.row.status)"
            >
              <el-icon><Switch /></el-icon>
              {{ getActionButtonText(scope.row.status) }}
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(scope.row)"
              :disabled="!canDelete(scope.row.status)"
            >
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      destroy-on-close
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="isView"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceType">
          <el-input v-model="form.serviceType" placeholder="请输入服务类型" />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入活动地点" />
        </el-form-item>
        <el-form-item label="活动时间" required>
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="开始时间"
                style="width: 100%"
                :disabled-date="disabledStartDate"
                value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">
            <span class="text-gray-500">至</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="结束时间"
                style="width: 100%"
                :disabled-date="disabledEndDate"
                value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="招募人数" prop="recruitNumber">
          <el-input-number v-model="form.recruitNumber" :min="1" :max="999" />
        </el-form-item>
        <el-form-item label="活动要求" prop="requirements">
          <el-input v-model="form.requirements" type="textarea" placeholder="请输入活动要求" />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入活动描述" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="主办方" required>
          <el-col :span="11">
            <el-form-item prop="organizerId">
              <el-input v-model="form.organizerId" placeholder="主办方ID" />
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">
            <span class="text-gray-500">-</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="organizerName">
              <el-input v-model="form.organizerName" placeholder="主办方名称" />
            </el-form-item>
          </el-col>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" v-if="!isView">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Calendar,
  Plus, 
  Search, 
  Refresh, 
  Edit, 
  View, 
  Delete,
  Switch
} from '@element-plus/icons-vue'
import { 
  getActivityList, 
  addActivity, 
  updateActivity, 
  deleteActivity,
  batchDeleteActivity,
  updateActivityStatus,
  getActivityDetail
} from '@/api/activity'

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: null
})

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRows = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const isView = ref(false)

// 表单数据
const form = reactive({
  id: '',
  title: '',
  description: '',
  location: '',
  startTime: '',
  endTime: '',
  recruitNumber: 1,
  requirements: '',
  contactPerson: '',
  contactPhone: '',
  serviceType: '',
  organizerId: '',
  organizerName: '',
  status: 0
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
  serviceType: [{ required: true, message: '请输入服务类型', trigger: 'blur' }],
  location: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  recruitNumber: [{ required: true, message: '请输入招募人数', trigger: 'blur' }],
  requirements: [{ required: true, message: '请输入活动要求', trigger: 'blur' }],
  description: [{ required: true, message: '请输入活动描述', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  organizerId: [{ required: true, message: '请输入主办方ID', trigger: 'blur' }],
  organizerName: [{ required: true, message: '请输入主办方名称', trigger: 'blur' }]
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',   // 待审核
    1: 'success',   // 进行中
    2: 'info',      // 已结束
    3: 'danger'     // 已取消
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '进行中',
    2: '已结束',
    3: '已取消'
  }
  return texts[status] || '未知'
}

// 获取操作按钮类型
const getActionButtonType = (status) => {
  if (status === 0) return 'success'  // 待审核 -> 通过
  if (status === 1) return 'warning'  // 进行中 -> 结束
  return 'info'
}

// 获取操作按钮文本
const getActionButtonText = (status) => {
  if (status === 0) return '通过'
  if (status === 1) return '结束'
  return '变更'
}

// 判断是否可以编辑
const canEdit = (status) => {
  return status === 0 || status === 1
}

// 判断是否可以删除
const canDelete = (status) => {
  return status !== 1
}

// 判断是否可以更改状态
const canChangeStatus = (status) => {
  return status === 0 || status === 1
}

// 获取下一个状态
const getNextStatus = (currentStatus) => {
  if (currentStatus === 0) return 1  // 待审核 -> 进行中
  if (currentStatus === 1) return 2  // 进行中 -> 已结束
  return currentStatus
}

// 禁用开始日期
const disabledStartDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 禁用结束日期
const disabledEndDate = (time) => {
  if (!form.startTime) return false
  return time.getTime() < new Date(form.startTime).getTime()
}

// 获取活动列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchForm.keyword,
      status: searchForm.status
    }
    const res = await getActivityList(params)
    if (res.code === 200) {
      tableData.value = res.data?.list || []
      total.value = res.data?.total || 0
    } else {
      ElMessage.error(res.message || '获取活动列表失败')
    }
  } catch (error) {
    console.error('获取活动列表失败：', error)
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.status = null
  handleSearch()
}

// 表格选择
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  form.recruitNumber = 1
  form.status = 0
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  isView.value = false
  resetForm()
}

// 新增活动
const handleAdd = () => {
  dialogTitle.value = '发布活动'
  dialogVisible.value = true
  isView.value = false
  resetForm()
}

// 编辑活动
const handleEdit = (row) => {
  if (!canEdit(row.status)) {
    ElMessage.warning('当前状态不允许修改')
    return
  }
  dialogTitle.value = '编辑活动'
  dialogVisible.value = true
  isView.value = false
  Object.keys(form).forEach(key => {
    form[key] = row[key] || ''
  })
}

// 查看活动
const handleView = async (row) => {
  try {
    const res = await getActivityDetail(row.id)
    if (res.code === 200) {
      dialogTitle.value = '查看活动详情'
      dialogVisible.value = true
      isView.value = true
      Object.keys(form).forEach(key => {
        form[key] = res.data[key] || ''
      })
    } else {
      ElMessage.error(res.message || '获取活动详情失败')
    }
  } catch (error) {
    console.error('获取活动详情失败：', error)
    ElMessage.error('获取活动详情失败')
  }
}

// 删除活动
const handleDelete = (row) => {
  if (!canDelete(row.status)) {
    ElMessage.warning('进行中的活动不允许删除')
    return
  }
  ElMessageBox.confirm('确认删除该活动吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteActivity(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchData()
      } else {
        ElMessage.error(res.message || '删除活动失败')
      }
    } catch (error) {
      console.error('删除活动失败：', error)
      ElMessage.error('删除活动失败')
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的活动')
    return
  }
  // 检查是否包含进行中的活动
  if (selectedRows.value.some(row => row.status === 1)) {
    ElMessage.warning('选中的活动中包含进行中的活动，不允许删除')
    return
  }
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 个活动吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id)
      const res = await batchDeleteActivity(ids)
      if (res.code === 200) {
        ElMessage.success('批量删除成功')
        fetchData()
      } else {
        ElMessage.error(res.message || '批量删除活动失败')
      }
    } catch (error) {
      console.error('批量删除活动失败：', error)
      ElMessage.error('批量删除活动失败')
    }
  })
}

// 更新状态
const handleStatusChange = (row) => {
  if (!canChangeStatus(row.status)) {
    ElMessage.warning('当前状态不允许变更')
    return
  }
  const newStatus = getNextStatus(row.status)
  const statusText = getStatusText(newStatus)
  ElMessageBox.confirm(`确认将活动状态变更为"${statusText}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await updateActivityStatus({
        id: row.id,
        status: newStatus
      })
      if (res.code === 200) {
        ElMessage.success('状态更新成功')
        fetchData()
      } else {
        ElMessage.error(res.message || '更新活动状态失败')
      }
    } catch (error) {
      console.error('更新活动状态失败：', error)
      ElMessage.error('更新活动状态失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (form.id) {
          res = await updateActivity(form)
        } else {
          res = await addActivity(form)
        }
        if (res.code === 200) {
          ElMessage.success('保存成功')
          dialogVisible.value = false
          fetchData()
        } else {
          ElMessage.error(res.message || '保存活动信息失败')
        }
      } catch (error) {
        console.error('保存活动信息失败：', error)
        ElMessage.error('保存活动信息失败')
      }
    }
  })
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.activity-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

.title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #fff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.title .el-icon {
  font-size: 28px;
  margin-right: 12px;
  color: #fff;
}

.search-card {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.table-card {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  padding: 16px 0;
}

:deep(.el-table) {
  margin-top: 16px;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #262626;
  font-weight: 600;
  padding: 16px 0;
}

:deep(.el-table td) {
  padding: 16px 0;
  color: #595959;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-button--link) {
  padding: 0 12px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--link:hover) {
  transform: translateY(-1px);
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px 24px;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
}

:deep(.el-dialog__title) {
  color: #fff;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 24px 32px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #262626;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #d9d9d9 inset;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #40a9ff inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #40a9ff inset;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 12px;
  height: 28px;
  line-height: 26px;
}

.text-center {
  text-align: center;
  line-height: 32px;
}

.text-gray-500 {
  color: #666;
}
</style> 